package com.example.myapplication;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import java.util.Random;

public class OdometerService extends Service {
    private double distanceMeters;
    private LocationManager locManager;
    private LocationListener locLister;
    private double Latitude;
    private double Longitude;
    @Override
    public void onCreate() {
        super.onCreate();
        locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        String provider = LocationManager.GPS_PROVIDER;
        locLister = new LocationListener() {
            private Location lastLocation;

            @Override
            public void onLocationChanged(@NonNull Location location) {
                if (lastLocation == null) {
                    lastLocation = location;
                }
                Latitude = location.getLatitude();
                Longitude = location.getLongitude();
                distanceMeters += location.distanceTo(lastLocation);
            }
        };
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            locManager.requestLocationUpdates(provider, 1000, 1, locLister);

        }
    }

    public OdometerService() {
    }


    //内部类时间IBinder用于向Acativity返回服务的引用
    //其中Binder实现了IBinder接口
    //内部类Binder返回了外部类的this指针，也就是获得服务的引用
    public class OdometerBinder extends Binder {
        OdometerService getOdometer()
        {
            return OdometerService.this;
        }
    }

    private IBinder binder = new OdometerBinder();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return binder;
    }

    /*
    先用随机数，在getdistance 调用random的nextdouble向activity返回一个随机的浮点数
    这样一来，我们的service有一个内部类binder，onbind方法，然后有一个getdistance方法
    服务内部，实例化一个自定义的binder，用于向activity返回服务的引用
     */
    private Random random = new Random();

    public double getDistance()
    {
        return distanceMeters/1000;
        //       return random.nextDouble();
    }

    //经度
    public double getLatitude()
    {
        return Latitude;
    }

    //纬度
    public double getLongitude() {
        return  Longitude;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(locManager !=null && locLister !=null)
        {
            locManager.removeUpdates(locLister);
        }
        locManager=null;
        locLister=null;
    }
}